'use strict';
import Base from './base.js';

export default class extends Base {
  async adminlistAction() {
    const orid = this.userinfo.departmentid;

    const list = await this.model('or_admin')
      .alias('a')
      .field('a.id, a.username, a.name, a.phone, a.remarks,r.id as rid, r.gradeid, r.remarks as miaoshu')
      .join('`think_or_rule_admin` r on r.id=a.groupid')
      .where({ 'a.departmentid': orid, 'a.ismain': 0 })
      .order('a.id DESC')
      .select();

    return this.json(list);
  }

  async addadminAction() {
    const data = this.post();
    const orid = this.userinfo.departmentid;

    if (data.id * 1) {
      const chongfu = await this.model('or_admin').where('(username="' + data.username + '" OR phone="' + data.phone + '") AND id!="' + data.id + '"').select();
      if (!think.isEmpty(chongfu)) {
        return this.fail('更改的帐号或手机号重复');
      }
      data.password = think.md5(data.password);
      const gengxin = await this.model('or_admin').update(data);
      return gengxin ? this.success('更改成功') : this.fail('更改失败');
    }

    const numbers = await this.model('or_admin').where({ departmentid: orid, ismain: 0 }).select();
    if (numbers.length > 15) {
      return this.fail('添加的管理员已达上线');
    }

    const repeat = await this.model('or_admin').where('(username="' + data.username + '" OR phone="' + data.phone + '")').select();

    if (!think.isEmpty(repeat)) {
      return this.fail('新增管理员帐号或手机号重复');
    }

    data.departmentid = orid;
    data.password = think.md5(data.password);
    const res = await this.model('or_admin').add(data);
    return res ? this.success('新增帐号成功') : this.fail('新增帐号失败');
  }

  async getgradelistAction() {
    const orid = this.userinfo.departmentid;
    const list = await this.model('or_rule_admin').where({ departmentid: orid }).order('gradeid ASC').select();
    return this.json(list);
  }

  async setgrageAction() {
    const data = this.post();

    const res = await this.model('or_admin').where({ id: data.id }).update({ groupid: data.groupid });
    return res ? this.success('设置权限成功') : this.fail('设置权限失败');
  }
}
